//
//  UIViewController+page.m
//  zxc
//
//  Created by delicious on 2018/1/13.
//  Copyright © 2018年 李李善. All rights reserved.
//

#import "UIViewController+page.h"
#import <objc/runtime.h>
#import "UIViewController+Action.h"
#import "UITableView+HD_NoList.h"
#import <MJRefresh/MJRefresh.h>
#import "MCViewController.h"
#import "MCTableViewController.h"
#import "MCCollectionViewController.h"
#import "MCVTableViewController.h"
#import "MCVCollectionViewController.h"
static char * vStartIndex = "vStartIndex";
static char * vCurrentPageIndex = "vCurrentPageIndex";
static char * vDataArr = "vDataArr";
static char * vInsertBackSection = "vInsertBackSection";
static char * vInsertFrontSection = "vInsertFrontSection";
static char * vSuccessBlock = "vSuccessBlock";
static char * vErrorBlock = "vErrorBlock";
static char * vFailedBlock = "vFailedBlock";
static char * vSuccessListBlock = "vSuccessListBlock";
static char * vErrorListBlock = "vErrorListBlock";
static char * vFailedListBlock = "vFailedListBlock";
static char * vTableView = "vTableView";
static char * vCollectionView = "vCollectionView";
static char * vIsShowDataImage = "vIsShowDataImage";
static char * vIsFirstSection = "vIsFirstSection";


@implementation UIViewController (page)


/** < 表格 > */
-(void)setCollectionView:(UICollectionView *)collectionView
{
    objc_setAssociatedObject(self, vCollectionView, collectionView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(UICollectionView *)collectionView
{
    return objc_getAssociatedObject(self, vCollectionView);
}



/** < 表格 > */
-(void)setTableView:(UITableView *)tableView
{
    objc_setAssociatedObject(self, vTableView, tableView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(UITableView *)tableView
{
    return objc_getAssociatedObject(self, vTableView);
}



/** < 默认第一页（分页） > */
-(NSUInteger)startIndex
{
    return [objc_getAssociatedObject(self, vStartIndex) integerValue];
}
-(void)setStartIndex:(NSUInteger)startIndex
{
    objc_setAssociatedObject(self, vStartIndex,@(startIndex), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(BOOL)isShowDataImage
{
    return [objc_getAssociatedObject(self, vIsShowDataImage) integerValue];
}
-(void)setIsShowDataImage:(BOOL)isShowDataImage
{
    objc_setAssociatedObject(self, vIsShowDataImage,@(isShowDataImage), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(BOOL)isFirstSection
{
    return [objc_getAssociatedObject(self, vIsFirstSection) integerValue];
}
-(void)setIsFirstSection:(BOOL)isFirstSection
{
    objc_setAssociatedObject(self, vIsFirstSection,@(isFirstSection), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


/** < 当前页（分页） > */
-(NSUInteger)currentPageIndex
{
    return [objc_getAssociatedObject(self, vCurrentPageIndex) integerValue];
}
-(void)setCurrentPageIndex:(NSUInteger)currentPageIndex
{
    objc_setAssociatedObject(self, vCurrentPageIndex,@(currentPageIndex), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}



/** < model数组 > */
-(NSMutableArray *)dataArr
{
    return objc_getAssociatedObject(self, vDataArr);
}
-(void)setDataArr:(NSMutableArray *)dataArr
{
    objc_setAssociatedObject(self, vDataArr, dataArr, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
}
/** < 插入最后几区 > */
-(NSInteger)insertBackSection
{
    return [objc_getAssociatedObject(self, vInsertBackSection) integerValue];
}

-(void)setInsertBackSection:(NSInteger)insertBackSection
{
    objc_setAssociatedObject(self, vInsertBackSection,@(insertBackSection), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSInteger)insertFrontSection
{
    return [objc_getAssociatedObject(self, vInsertFrontSection) integerValue];
}
-(void)setInsertFrontSection:(NSInteger)insertFrontSection
{
    objc_setAssociatedObject(self, vInsertFrontSection,@(insertFrontSection), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

/* < successBlock> */
-(successBlock)successBlock
{
    successBlock block = objc_getAssociatedObject(self, vSuccessBlock);
    if (!block) {
        WSELF(weakSelf);
        block = ^(id data) {
            if ([data isKindOfClass:[NSArray class]]) {
                [self.dataArr addObjectsFromArray:data];
            }else if ([data isKindOfClass:[NSObject class]])
            {
                weakSelf.model = data;
            }
            [weakSelf.collectionView reloadData];
            [weakSelf.tableView reloadData];
        };
    }
    return block;
}

-(void)setSuccessBlock:(successBlock)successBlock
{
    objc_setAssociatedObject(self, vSuccessBlock, successBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

-(errorBlock)errorBlock
{
    errorBlock block = objc_getAssociatedObject(self, vErrorBlock);
    if (!block) {
        WSELF(weakSelf);
        block = ^(NSString * error)
        {
#if BaseClass == 0
            [weakSelf showMessage:error];
#endif
        };
    }
    return block;
    
}

-(void)setErrorBlock:(errorBlock)errorBlock
{
    objc_setAssociatedObject(self, vErrorBlock,errorBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

-(failedBlock)failedBlock
{
    failedBlock block = objc_getAssociatedObject(self, vFailedBlock);
    if (!block) {
        WSELF(weakSelf);
        block = ^(NSString * error)
        {
#if BaseClass == 0
            [weakSelf showMessage:error];
#endif
        };
    }
    return block;
    
}

-(void)setFailedBlock:(failedBlock)failedBlock
{
    objc_setAssociatedObject(self, vFailedBlock,failedBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}





- (void)NeedResetNoView{
    if (self.dataArr.count>0) {
        [self.tableView dismissNoView];
    }else{
        [self.tableView showNoView:@"怎么没有数据???" image:nil certer:CGPointZero];
    }
}


- (void (^)())addNewCellDataSuccessBlock:(UIView *)view
{
    WSELF(weakSelf);
    return ^(NSArray *dataList) {
        
        if (weakSelf) {
      
            if ([view isKindOfClass:[UITableView class]]) {
                UITableView *tableView= (id)view;
                tableView.mj_footer.hidden = NO;
                if (dataList&&[dataList isKindOfClass:[NSArray class]]) {
                    
                    if (dataList.count > 0) {
                         UITableViewController *vc = (id)weakSelf;
                        if (weakSelf.isFirstSection==YES) {
                            NSInteger section = weakSelf.insertBackSection;
                           NSInteger rowCount = [vc tableView:tableView numberOfRowsInSection:section];
                            NSMutableArray *arr = [[NSMutableArray alloc]initWithCapacity:dataList.count];
                            for (int n = 0; n < dataList.count; ++n) {
                                NSIndexPath *idxp = [NSIndexPath indexPathForItem:n+rowCount inSection:section];
                                [arr addObject:idxp];
                            }
                            
                            [weakSelf.dataArr addObjectsFromArray:dataList];
                            [tableView insertRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationFade];
                        }
                        else
                        {
                            
                            NSMutableIndexSet *arr = [NSMutableIndexSet indexSet];
                           NSInteger rowCount = [vc numberOfSectionsInTableView:tableView];
                            for (int n = 0; n < dataList.count; ++n) {
                                [arr addIndex:rowCount+n];
                            }
                            
                            [weakSelf.dataArr addObjectsFromArray:dataList];
                            [tableView insertSections:arr withRowAnimation:UITableViewRowAnimationFade];
                        }
                        
                        //- (void)insertSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;
                        weakSelf.currentPageIndex++;
                    }else
                    {
                        [tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                }
                [weakSelf endRefreshing:view];
                
                if ( weakSelf.isShowDataImage == YES) {
                    [weakSelf NeedResetNoView];
                }
  
            }else
            {
                UICollectionView *collectionView= (id)view;
                weakSelf.collectionView.mj_footer.hidden = NO;
                
                if (dataList&&[dataList isKindOfClass:[NSArray class]]) {
                    if (dataList.count > 0) {
                        
                        NSInteger section = self.insertBackSection;
                        
                        UICollectionViewController *vc = (id)weakSelf;
                        NSInteger rowCount = [vc collectionView:collectionView numberOfItemsInSection:section];

                        NSMutableArray *arr = [[NSMutableArray alloc]initWithCapacity:dataList.count];
                        for (int n = 0; n < dataList.count; ++n) {
                            NSIndexPath *idxp = [NSIndexPath indexPathForItem:n+rowCount inSection:section];
                            [arr addObject:idxp];
                        }

                        [weakSelf.dataArr addObjectsFromArray:dataList];
                        [collectionView insertItemsAtIndexPaths:arr];
                        weakSelf.currentPageIndex++;

                        [collectionView reloadData];
                    }
                }
                else
                {
                    [collectionView.mj_footer endRefreshingWithNoMoreData];
                }
                
                [weakSelf endRefreshing:view];
            }
            
        }
      
    };
}



- (void (^)())setupCellDataSuccessBlock:(UIView*)view
{
    WSELF(weakSelf);
    return ^(NSArray *dataList) {
        
        if (weakSelf) {
        [weakSelf.dataArr removeAllObjects];
            
            if ([view isKindOfClass:[UITableView class]]) {
                UITableView *tableView= (id)view;
                if (dataList&&[dataList isKindOfClass:[NSArray class]]) {
                    
                    if (dataList.count > 0) {
                        [weakSelf.dataArr addObjectsFromArray:dataList];
                        //                [weakSelf onHiddenBackView];
                        [tableView.mj_footer resetNoMoreData];
                        tableView.mj_footer.hidden = NO;
                        weakSelf.currentPageIndex = weakSelf.startIndex+1;
                    }
                }
                
                [tableView reloadData];
                [weakSelf endRefreshing:tableView];
                        if ( weakSelf.isShowDataImage == YES) {
                [weakSelf NeedResetNoView];
                        }
            }else
            {
                UICollectionView *collectionView= (id)view;
                if (dataList&&[dataList isKindOfClass:[NSArray class]]) {
                    if ( dataList.count > 0) {
                        [weakSelf.dataArr addObjectsFromArray:dataList];
                        
                        [collectionView.mj_footer resetNoMoreData];
                        collectionView.mj_footer.hidden = NO;
                        weakSelf.currentPageIndex = weakSelf.startIndex+1;
                    }
                }
                
                [collectionView reloadData];
                [weakSelf endRefreshing:collectionView];
            }
            }
        
    };
}




- (void (^)())setupCellDataFailureBlock:(UIView *)view
{
    WSELF(weakSelf);
    return ^(NSError *error) {
        if (weakSelf) {
            [weakSelf endRefreshing:view];
        }
    };
}


- (void (^)())addNewCellDataFailureBlock:(UIView *)view
{WSELF(weakSelf);
    return ^(NSError *error) {
        if (weakSelf) {
            
            [weakSelf endRefreshing:view];
            
        }
        
    };
}



- (void)endRefreshing:(UIView *)view
{
    
    if ([view isKindOfClass:[UICollectionView class]]) {
        UICollectionView *collectionView = (id)view;
        if (collectionView.mj_header.isRefreshing) {
            [collectionView.mj_header endRefreshing];
        }
        if (collectionView.mj_footer.isRefreshing) {
            [collectionView.mj_footer endRefreshing];
        }
    }
    else
    {
        UITableView *tableView = (id)view;
        if (tableView.mj_header.isRefreshing) {
            [tableView.mj_header endRefreshing];
        }
        if (tableView.mj_footer.isRefreshing) {
            [tableView.mj_footer endRefreshing];
        }
    }
    
    
}



/* < subcessListBlock> */
-(successListBlock)subcessListBlock
{
    successListBlock block = objc_getAssociatedObject(self, vSuccessListBlock);
    if (!block) {
        WSELF(weakSelf);
        block = ^(id data,NSInteger pageNum) {
            
            if ([data isKindOfClass:[NSArray class]]) {
                if (pageNum==weakSelf.startIndex) {
                    [weakSelf setupCellDataSuccessBlock:weakSelf.tableView](data);
                }
                else
                {
                    [weakSelf addNewCellDataSuccessBlock:weakSelf.tableView](data);
                }
            }else if ([data isKindOfClass:[NSObject class]])
            {
                weakSelf.model = data;
                
                [weakSelf.collectionView reloadData];
                [weakSelf.tableView reloadData];
            }
        };
    }
    return block;
}

-(void)setSubcessListBlock:(successListBlock)subcessListBlock
{
    objc_setAssociatedObject(self, vSuccessListBlock, subcessListBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}



/* < vErrorListBlock> */
-(errorBlock)errorListBlock
{
    errorBlock block = objc_getAssociatedObject(self, vErrorListBlock);
    if (!block) {
        WSELF(weakSelf);
        block = ^(NSString *error){
    
            if (weakSelf) {

                UIView *view;
            
                if ([weakSelf isKindOfClass:[MCVTableViewController class]]||[weakSelf isKindOfClass:[MCTableViewController class]]) {
                    view = weakSelf.tableView;
                    
                }
                else
                {
                    view = weakSelf.collectionView;
                }

            [weakSelf setupCellDataFailureBlock:view];
            [weakSelf addNewCellDataFailureBlock:view];
            [weakSelf showMessage:error];
                
            }
        };
    }
    return block;
}

-(void)setErrorListBlock:(errorBlock)errorListBlock
{
    objc_setAssociatedObject(self, vErrorListBlock,errorListBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}




/* < vFailedListBlock> */
-(failedBlock)failedListBlock
{
    failedBlock block = objc_getAssociatedObject(self, vFailedListBlock);
    if (!block) {
        WSELF(weakSelf);
        block = ^(NSString *error){
            if (weakSelf) {
                
                UIView *view;
                
                if ([weakSelf isKindOfClass:[MCVTableViewController class]]||[weakSelf isKindOfClass:[MCTableViewController class]]) {
                    view = weakSelf.tableView;
                    
                }
                else
                {
                    view = weakSelf.collectionView;
                }
                
                [weakSelf setupCellDataFailureBlock:view];
                [weakSelf addNewCellDataFailureBlock:view];
                [weakSelf showMessage:error];
                
            }
        };
    }
    return block;
}

-(void)setFailedListBlock:(failedBlock)failedListBlock
{
    objc_setAssociatedObject(self, vFailedListBlock,failedListBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}




-(id)modelForIndexPath:(NSIndexPath *)indePath
{
    if (self.dataArr.count==0) {
        return nil;
    }
    return [self.dataArr objectAtIndex:indePath.row];
}

-(void)removeDataArrAtIndex:(NSIndexPath *)index
{
    if (self.dataArr.count==0) {
        return;
    }
    [self.dataArr removeObjectAtIndex:index.row];
    if (self.collectionView) {
        
        [self.collectionView deleteItemsAtIndexPaths:@[index]];
    }else
    {
        [self.tableView deleteRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];
    }
    
}


- (void)onUpdateCell:(UIView *)cell model:(id _Nullable )model atIndexPath:(NSIndexPath *_Nullable)indexPath
{
    if ([cell isKindOfClass:[UITableViewCell class]]) {
        BaseTableViewCell *cell1 = (id)cell;
        [cell1 update:model forTableView:self.tableView AtIndexPath:indexPath];
    }else
    {
        UICollectionViewCell *cell1 = (id)cell;
        [cell1 update:model forCollectionView:self.collectionView AtIndexPath:indexPath];
    }
    
}


@end
